<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Exception;

class AdministratorController extends Controller
{
    //后台账号增删改查
    public function lists(){
    	$admin_lists = Db::table('admin')->where('level','!=','1')->paginate(15);

    	return view('admin_lists',['admin_lists'=>$admin_lists]);
    }

    //添加产品
    public function admin_add(Request $request){

    	return view('admin_add');
    }

    //添加新闻动作
    public function add_admin_do(Request $request){
    	$input = $request->input();
    	if(empty($input['pwd']))throw new Exception("请填写密码！");

    	$users = Db::table('admin')->where('account','=',$input['account'])->first();

    	if(!isset($input['id'])){
    		if($input['account'] == 'admin'){
    			throw new Exception("该账号名已存在了！");
    		}

    		if(!empty($users->id)){
    			throw new Exception("该账号名已存在了！");
    		}
    	}

    	$input['pwd'] = Hash::make($input['pwd']);
    	$input['level'] = 2;

    	if(empty($input['id'])){
    		Db::table('admin')->insert($input);
    	}else{
    		Db::table('admin')->where('id','=',$input['id'])->update($input);
    	}

    	return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
    }

    //编辑新闻
    public function admin_edit(Request $request,$id){
    	$where[] = ['id','=',$id];
    	$admin_edit = Db::table('admin')->where($where)->first();
    	
    	return view('admin_edit',['admin_edit'=>$admin_edit,'id'=>$id]);
    }

    //删除新闻
    public function admin_del(Request $request,$id){
    	$where[] = ['id','=',$id];
    	Db::table('admin')->where($where)->delete();

    	return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
    }
}
